package com.base.app_core.base.impl;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.base.app_core.App;
import com.base.app_core.R;
import com.base.app_core.View.LoadingPage;
import com.base.app_core.base.BaseView;
import com.base.app_core.ioc.component.BaseViewComponent;
import com.base.app_core.ioc.module.BaseModule;
import com.base.app_core.model.Paginated;
import com.base.app_core.util.AppConstants;
import com.gyf.barlibrary.ImmersionBar;
import com.tencent.bugly.crashreport.CrashReport;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by xiangheng.song on 2017/2/28.
 */

public abstract class BaseFragment<T extends BasePresenter> extends Fragment implements BaseView {

    private View mLoadProess = null;

    public LoadingPage mLoadingPage;

    protected boolean mIsVisible = false;     // fragment是否显示了

    protected boolean isPrepared = false;

    protected View contentView;

    protected Unbinder munbinder = null;

    private LayoutInflater inflater;

    public LayoutInflater getInflater() {
        return inflater;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setupComponent();
        attachView();
        if (mLoadingPage == null) {
            mLoadingPage = new LoadingPage(getContext(), isNeedShowLoading()) {
                @Override
                protected void initView() {
                    BaseFragment.this.contentView = this.contentView;
                    munbinder = ButterKnife.bind(BaseFragment.this, contentView);
                    BaseFragment.this.initView();
                    InitQinRuShi(this.contentView);
                }

                @Override
                protected void loadData() {
                    BaseFragment.this.loadData();
                }

                @Override
                protected int getLayoutId() {
                    return BaseFragment.this.getLayoutId();
                }
            };
        }
        isPrepared = true;
        this.inflater = inflater;
        return mLoadingPage;
    }

    private TextView mheadcentercontent;

    protected void setToolBar(String... title) {
        if (null == toolbar)
            toolbar = (Toolbar) contentView.findViewById(R.id.toolbar);
        mheadcentercontent = (TextView) contentView.findViewById(R.id.center_title);
        if (mheadcentercontent != null)
            mheadcentercontent.setText(title[0]);
        ImageView close_category_list = (ImageView) contentView.findViewById(R.id.close_category_list);
        if (null != close_category_list) {
            close_category_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().onBackPressed();
                }
            });
            if (title.length > 1 && title[1].equals(AppConstants.Const.UNDISCLOSE)) {
                close_category_list.setVisibility(View.GONE);
            }
        }

        TextView center_title = (TextView) contentView.findViewById(R.id.center_title);
        if (null != center_title)
            center_title.setText(title[0]);

    }

    protected boolean isNeedShowLoading() {//请求之前h显示请求提醒
        return false;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (munbinder != null) {
            munbinder.unbind();
            munbinder = null;
        }
    }

//  private CompositeSubscription mCompositeSubscription;

    //用于添加rx的监听的在onDestroy中记得关闭不然会内存泄漏。
//  @Override
//  public void bindToLifecycle(Subscription subscription) {
//    if (this.mCompositeSubscription == null) {
//      this.mCompositeSubscription = new CompositeSubscription();
//    }
//    this.mCompositeSubscription.add(subscription);
//  }

    @Override
    public void onDestroy() {
        super.onDestroy();
//    if (this.mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
//      this.mCompositeSubscription.unsubscribe();
//    }
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    /**
     * 在这里实现Fragment数据的缓加载.
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {//fragment可见
            mIsVisible = true;
            onVisible();
        } else {//fragment不可见
            mIsVisible = false;
            onInvisible();
        }
    }
//

    /**
     * 是否在Fragment使用沉浸式
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return false;
    }

    protected ImmersionBar mImmersionBar;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null)
            mImmersionBar.init();
    }

    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
    }

    @Override
    public void setState(int state) {
        if (null != mLoadingPage) {
            mLoadingPage.showPage(state);
        }
    }

    protected void onInvisible() {
    }

    /**
     * 显示时加载数据,需要这样的使用
     * 注意声明 isPrepared，先初始化
     * 生命周期会先执行 setUserVisibleHint 再执行onActivityCreated
     * 在 onActivityCreated 之后第一次显示加载数据，只加载一次
     */

    protected void onVisible() {
        if (isPrepared) {
            loadData();//根据获取的数据来调用showView()切换界面
        }
    }

    /**
     * 3
     * 子类关于View的操作(如setAdapter)都必须在这里面，会因为页面状态不为成功，而binding还没创建就引用而导致空指针。
     */
    protected void initView() {

    }

    /**
     * 1
     * 根据网络获取的数据返回状态，每一个子类的获取网络返回的都不一样，所以要交给子类去完成
     */
    protected void loadData() {
        if (null != mLoadingPage && isNeedShowLoading()) {
            mLoadingPage.showPage(AppConstants.STATE_LOADING);
        }
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
    }

    @Override
    public void onLoginSuccess() {

    }

    @Override
    public void notifyError(String errorCode, String content) {
        if (null != mLoadingPage && needShowError()) {
            mLoadingPage.showErrorPage(content);
        }
        dismissProgress();
    }

    protected boolean needShowError() {
        return true;
    }

    protected void setupComponent() {

    }

    protected abstract int getLayoutId();

    @Inject
    protected T mPresenter;

    protected void attachView() {
        if (mPresenter != null) mPresenter.attachView(this);
    }

    protected BaseViewComponent getBaseViewComponent() {
        return App.getApp().getAppComponent().plus(getActivityModule());
    }

    protected BaseModule getActivityModule() {
        return new BaseModule(this);
    }

//    private ToastView mtoast = null;

    protected void showToast(String content) {
        Toast toast = Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
//        if (null == mtoast) {
//            mtoast = new ToastView(getActivity(), content);
//            mtoast.setGravity(Gravity.CENTER, 0, 0);
//        } else {
//            mtoast.setTextContent(content);
//        }
//        mtoast.show();
    }


    private ViewGroup getRootView(Activity context) {
        if (context == null || context.isFinishing() || context.getWindow() == null) {
            return null;
        }

        return (ViewGroup) ((ViewGroup) getActivity().getWindow()
                .getDecorView()
                .findViewById(android.R.id.content)).getChildAt(0);
    }

    //操作过程使用的
    protected void showProgress() {//显示进度提醒
        if (getActivity().isFinishing()) {
            return;
        }
        if (null == mLoadProess) {
            mLoadProess = LayoutInflater.from(getActivity()).inflate(R.layout.loading_view_layout, null);
        }
        if (mLoadProess != null && null == mLoadProess.getParent()) {
            FrameLayout.LayoutParams params =
                    new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
            ViewGroup rootView = getRootView(getActivity());
            if (rootView != null) {
                rootView.addView(mLoadProess, params);
            }
        }
    }

    protected void dismissProgress() {//关闭进度条
        FragmentActivity activity = getActivity();
        if (activity == null) {
            return;
        }

        if (activity.isFinishing()) {
            return;
        }

        try {
            ViewGroup rootView = getRootView(activity);
            if (null != mLoadProess && rootView != null) {
                rootView.removeView(mLoadProess);
            }
        } catch (Exception e) {
            e.printStackTrace();
            CrashReport.postCatchedException(e);
        }

    }

    protected Toolbar toolbar = null;

    public void InitQinRuShi(View view) {
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        if (isImmersionBarEnabled())
            initImmersionBar();
    }

    protected boolean openQinRuShiUi() {
        return false;
    }

    protected View getEmptyView(RecyclerView view, String maintile, String subtitle, View.OnClickListener onClickListener) {
        View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.view_empty_layout, null);
        TextView textmain = (TextView) view1.findViewById(R.id.maintitile);
        TextView textsub = (TextView) view1.findViewById(R.id.subtitile);
        textmain.setText(maintile);
        textsub.setText(subtitle);
        ((ViewGroup) view.getParent()).addView(view1, -1);
        if (null != onClickListener)
            view1.setOnClickListener(onClickListener);
        view1.setVisibility(View.GONE);
        return view1;
    }
}
